package com.celinio.readprops;
import java.io.File;
import java.util.Iterator;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;
import org.apache.log4j.Logger;


/**
 * This class reads properties that are stored in a file outside the webapp
 * @author Celinio Fernandes
 *
 */
public class ReadExternalPropertiesUtil {
		
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(ReadExternalPropertiesUtil.class);

	private static final String PROPERTIES_FILE = "config.properties";
	private static final String ENV_VAR = "PROPERTIES_APP";
	public static String propertiesFolder;
	public static PropertiesConfiguration propertiesConfig  = null;
	
	
	/**
	 * Private constructor to prevent initialization of this utility class.
	 */
	 private ReadExternalPropertiesUtil() {
	 }

	/**
	 *  Method to load the properties files
	 * @return
	 */
	public static boolean initFile(long reloadInterval){
		boolean initProp=false;
	
		logger.info("Environment variable = "+ENV_VAR);	
		propertiesFolder = System.getProperty(ENV_VAR);
		
		if(propertiesFolder==null)
		{
			propertiesFolder = System.getenv(ENV_VAR);
		}
		
		logger.info(propertiesFolder);
		
		if(propertiesFolder!=null && folderExists(propertiesFolder)){
			
			String propertiesFile = propertiesFolder+File.separator+PROPERTIES_FILE;
			
			if(fileExists(propertiesFile))
			{		
								
				try {					
					
					propertiesConfig = new PropertiesConfiguration(propertiesFile);
					//propertiesConfig = new PropertiesConfiguration();
					//propertiesConfig.setFileName(propertiesFile);
					
									
					if (reloadInterval > 0) {
						logger.info("reloadInterval >0");
						FileChangedReloadingStrategy strategy  = null;
						strategy  = new FileChangedReloadingStrategy();
						strategy.setRefreshDelay(reloadInterval);	// Set the minimal time between two reloadings, in milliseconds. DOES NOT WORK !
						propertiesConfig.setReloadingStrategy(strategy);
					
						
						propertiesConfig.setDelimiterParsingDisabled(true);
						//propertiesConfig.load();
						logger.debug("Loading the following properties :");
						print();
						logger.info("Properties loaded..");
	
					}  else {
						propertiesConfig.setReloadingStrategy(new FileChangedReloadingStrategy());
						propertiesConfig.setDelimiterParsingDisabled(true);
						//propertiesConfig.load();	
						logger.debug("Loading the following properties :");
						print();
						logger.info("Properties loaded..");
					}								
				
					initProp=true;
				} catch (ConfigurationException e) {
					logger.error("Error loading the properties");
				}
		
			}else{
				logger.error("The properties file does not exist");
			}
		}else{
			logger.info("The folder does not exist");
		}
			return initProp;
	}

	private static boolean folderExists(String folderName){
		File f = new File(folderName);
		return f.exists() && f.isDirectory();
	}

	
	/**
	* Method that checks whether a file exists or not
	*  @param String filename
	*  @return boolean, true if the file exists
	* */
	private static boolean fileExists(String fileName){
		File f = new File(fileName);
		return f.exists() && f.canRead();
	}
	
	public static String getProperty(String property){
		return propertiesConfig.getString(property);
	}
	
	private static void print() {
		for (Iterator<String> keys = propertiesConfig.getKeys(); keys.hasNext();) {
			String key = keys.next();
			logger.debug(key + " = " + propertiesConfig.getProperty(key));
		}
	}

}
